﻿using System;
using System.Collections.Generic;
using System.Text;

namespace HZY.Logic.Core
{
    using System.IO;
    using HZY.DbExtensions;
    using HzySql.Interface;
    using NPOI.HSSF.UserModel;
    using NPOI.SS.UserModel;

    public class LogicBase
    {
        public HzySqlDbContext db { get; }

        public List<ISqlContext> iSqlContexts = new List<ISqlContext>();

        public LogicBase(HzySqlDbContext dbContext)
        {
            this.db = dbContext;
        }

        #region 导出 Excel

        protected virtual byte[] ExportExcelByTableViewModel(TableViewModel tableViewModel)
        {
            HSSFWorkbook workbook = new HSSFWorkbook();
            ISheet sheet = workbook.CreateSheet();
            //数据
            var data = tableViewModel.DataSource;
            var cols = tableViewModel.Cols;
            //填充表头
            IRow dataRow = sheet.CreateRow(0);
            foreach (var item in cols)
            {
                if (!item.Show) continue;
                var index = cols.IndexOf(item);
                dataRow.CreateCell(index).SetCellValue(item.Title);
            }
            //填充内容
            for (int i = 0; i < data.Count; i++)
            {
                var item = data[i];
                dataRow = sheet.CreateRow(i + 1);
                foreach (var col in cols)
                {
                    if (!col.Show) continue;
                    var index = cols.IndexOf(col);
                    var value = item[col.DataIndex];
                    dataRow.CreateCell(index).SetCellValue(value == null ? "" : value.ToString());
                }
            }
            //填充byte
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                return ms.ToArray();
            }
        }

        #endregion


    }
}
